import React, { useState, useEffect } from 'react';
import { useParams, Link } from 'react-router-dom';
import { ArrowLeft, ExternalLink, TrendingUp, MessageCircle, Eye, Share, Clock, Tag } from 'lucide-react';
import TrendChart from '../components/TrendChart';
import Loading from '../components/Loading';
import { getHotspotDetail } from '../services/api';
import { formatDateTime, formatDistanceToNow } from '../utils/dateUtils';

const HotspotDetailPage = () => {
  const { id } = useParams();
  const [hotspot, setHotspot] = useState(null);
  const [relatedHotspots, setRelatedHotspots] = useState([]);
  const [trendData, setTrendData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchHotspotDetail = async () => {
      try {
        setLoading(true);
        setError(null);

        const detailData = await getHotspotDetail(id);

        setHotspot(detailData.hotspot);
        setTrendData(detailData.trendData || []);
        setRelatedHotspots([]); // 相关热点功能暂不可用
      } catch (error) {
        console.error('获取热点详情失败:', error);
        setError('获取热点详情失败，请重试');
      } finally {
        setLoading(false);
      }
    };

    if (id) {
      fetchHotspotDetail();
    }
  }, [id]);

  const getPlatformColor = (platform) => {
    const colors = {
      '微博': 'bg-red-100 text-red-800 border-red-200',
      '知乎': 'bg-blue-100 text-blue-800 border-blue-200',
      '百度': 'bg-green-100 text-green-800 border-green-200',
      'B站': 'bg-pink-100 text-pink-800 border-pink-200',
      '抖音': 'bg-purple-100 text-purple-800 border-purple-200',
    };
    return colors[platform] || 'bg-gray-100 text-gray-800 border-gray-200';
  };

  const formatNumber = (num) => {
    if (num >= 10000) {
      return (num / 10000).toFixed(1) + 'w';
    }
    return num.toLocaleString();
  };

  const handleShare = async () => {
    if (navigator.share) {
      try {
        await navigator.share({
          title: hotspot.title,
          text: hotspot.description,
          url: window.location.href,
        });
      } catch (error) {
        console.log('分享失败:', error);
      }
    } else {
      // 复制链接到剪贴板
      await navigator.clipboard.writeText(window.location.href);
      alert('链接已复制到剪贴板');
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50">
        <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <Loading size="large" text="正在加载热点详情..." />
        </div>
      </div>
    );
  }

  if (error || !hotspot) {
    return (
      <div className="min-h-screen bg-gray-50">
        <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <div className="text-center py-12">
            <TrendingUp className="h-16 w-16 text-gray-300 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-gray-900 mb-2">
              {error || '热点不存在'}
            </h3>
            <Link 
              to="/" 
              className="text-primary-600 hover:text-primary-700 transition-colors"
            >
              返回首页
            </Link>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* 返回按钮 */}
        <Link 
          to="/"
          className="inline-flex items-center space-x-2 text-gray-600 hover:text-primary-600 transition-colors mb-6"
        >
          <ArrowLeft className="h-4 w-4" />
          <span>返回首页</span>
        </Link>

        {/* 主要内容 */}
        <div className="bg-white rounded-lg border border-gray-200 overflow-hidden mb-8">
          {/* 头部信息 */}
          <div className="p-6 border-b border-gray-200">
            <div className="flex items-start justify-between mb-4">
              <span className={`px-3 py-1 text-sm font-medium rounded-full border ${getPlatformColor(hotspot.platform)}`}>
                {hotspot.platform}
              </span>
              <button
                onClick={handleShare}
                className="flex items-center space-x-1 px-3 py-2 text-gray-600 hover:text-primary-600 hover:bg-gray-50 rounded-lg transition-colors"
              >
                <Share className="h-4 w-4" />
                <span className="text-sm">分享</span>
              </button>
            </div>

            <h1 className="text-2xl md:text-3xl font-bold text-gray-900 mb-4 leading-tight">
              {hotspot.title}
            </h1>

            {hotspot.description && (
              <p className="text-gray-600 text-lg mb-6 leading-relaxed">
                {hotspot.description}
              </p>
            )}

            {/* 统计数据 */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 p-4 bg-gray-50 rounded-lg">
              <div className="text-center">
                <div className="flex items-center justify-center mb-1">
                  <Eye className="h-4 w-4 text-gray-500 mr-1" />
                  <span className="text-sm font-medium text-gray-500">浏览量</span>
                </div>
                <span className="text-xl font-bold text-gray-900">
                  {formatNumber(hotspot.views || 0)}
                </span>
              </div>
              <div className="text-center">
                <div className="flex items-center justify-center mb-1">
                  <MessageCircle className="h-4 w-4 text-gray-500 mr-1" />
                  <span className="text-sm font-medium text-gray-500">讨论数</span>
                </div>
                <span className="text-xl font-bold text-gray-900">
                  {formatNumber(hotspot.comments || 0)}
                </span>
              </div>
              <div className="text-center">
                <div className="flex items-center justify-center mb-1">
                  <TrendingUp className="h-4 w-4 text-gray-500 mr-1" />
                  <span className="text-sm font-medium text-gray-500">热度</span>
                </div>
                <span className="text-xl font-bold text-red-500">
                  {hotspot.heat}°
                </span>
              </div>
              <div className="text-center">
                <div className="flex items-center justify-center mb-1">
                  <Clock className="h-4 w-4 text-gray-500 mr-1" />
                  <span className="text-sm font-medium text-gray-500">更新时间</span>
                </div>
                <span className="text-sm text-gray-900">
                  {formatDistanceToNow(hotspot.updatedAt)}
                </span>
              </div>
            </div>
          </div>

          {/* 标签 */}
          {hotspot.tags && hotspot.tags.length > 0 && (
            <div className="px-6 py-4 border-b border-gray-200">
              <div className="flex items-center space-x-2 mb-2">
                <Tag className="h-4 w-4 text-gray-500" />
                <span className="text-sm font-medium text-gray-700">相关标签</span>
              </div>
              <div className="flex flex-wrap gap-2">
                {hotspot.tags.map((tag, index) => (
                  <span
                    key={index}
                    className="px-2 py-1 bg-primary-100 text-primary-800 text-sm rounded-md"
                  >
                    #{tag}
                  </span>
                ))}
              </div>
            </div>
          )}

          {/* 原文链接 */}
          {hotspot.url && (
            <div className="px-6 py-4">
              <a
                href={hotspot.url}
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex items-center space-x-2 px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition-colors"
              >
                <ExternalLink className="h-4 w-4" />
                <span>查看原文</span>
              </a>
            </div>
          )}
        </div>

        {/* 趋势图表 */}
        {trendData.length > 0 && (
          <div className="mb-8">
            <TrendChart data={trendData} title={`"${hotspot.title}" 热度趋势`} />
          </div>
        )}

        {/* 相关热点 */}
        {relatedHotspots.length > 0 && (
          <div className="bg-white rounded-lg border border-gray-200 p-6">
            <h2 className="text-lg font-semibold text-gray-900 mb-4">相关热点</h2>
            <div className="space-y-3">
              {relatedHotspots.slice(0, 5).map((related, index) => (
                <Link
                  key={related.id}
                  to={`/hotspot/${related.id}`}
                  className="block p-3 rounded-lg hover:bg-gray-50 transition-colors"
                >
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <h3 className="font-medium text-gray-900 mb-1 line-clamp-2">
                        {related.title}
                      </h3>
                      <div className="flex items-center space-x-4 text-sm text-gray-500">
                        <span className={`px-2 py-1 text-xs rounded-full ${getPlatformColor(related.platform)}`}>
                          {related.platform}
                        </span>
                        <span>{related.heat}°</span>
                        <span>{formatDistanceToNow(related.updatedAt)}</span>
                      </div>
                    </div>
                    <span className="text-sm text-gray-400 ml-4">#{index + 1}</span>
                  </div>
                </Link>
              ))}
            </div>
          </div>
        )}

        {/* 页面底部信息 */}
        <div className="mt-8 text-center text-sm text-gray-500">
          <p>最后更新: {formatDateTime(hotspot.updatedAt)}</p>
          <p className="mt-1">数据来源: {hotspot.platform}</p>
        </div>
      </div>
    </div>
  );
};

export default HotspotDetailPage;